package demo10;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2023-04-13
 * Time: 6:42
 */
class ListNode{
    int val;
    ListNode next;
    public ListNode(int val){
        this.val = val;
    }


}
public class Test01 {
    public ListNode addInList(ListNode head1,ListNode head2){
        ListNode sHead1 = resverse(head1);
        ListNode sHead2 = resverse(head2);
        ListNode phead = new ListNode(-1);
        int flag = 0;
        //两链都为位空
        while (sHead1 != null || sHead2 != null){
            int sum = 0;
            if(sHead1 != null){
                sum += sHead1.val;
                sHead1 = sHead1.next;
            }
            if(sHead2 != null){
                sum += sHead2.val;
                sHead2 = sHead2.next;
            }

            sum += flag;
            ListNode cur = new ListNode(sum % 10);
            cur.next = phead.next;
            phead.next = cur;
            //标记进位
            flag = sum / 10;

        }
        //处理进位
        if(flag != 0){
            ListNode cur = new ListNode(flag);
            cur.next = phead.next;
            phead.next = cur;
        }
        return phead.next;
    }
    //进行反转
    private ListNode resverse(ListNode head) {
        ListNode pHead = new ListNode(-1);
        pHead.next = head;
        ListNode cur = head;
        ListNode pre = pHead;
        if(cur == null){
            return head;
        }
        while (cur.next != null){
            ListNode tmp = cur.next;
            cur.next = tmp.next;
            tmp.next = pre.next;
            pre.next = tmp;
        }
        return pHead.next;
    }
}
